/*******************************************************************************
*  file    : backupserver.cpp
*  created : 22.07.2013
*  author  : 
*******************************************************************************/

#include "backupserver.hpp"
#include <QDebug>
#include <QTimer>
#include <QLocalServer>
#include <QCoreApplication>
#include <QFile>
#include <QScopedPointer>
#include <option_parser.hpp>

BackupServer::BackupServer(QObject *parent) :
    QObject(parent)
{
    socket_ = new QLocalSocket(this);
    server_ = new QLocalServer(this);
    connect(server_, SIGNAL(newConnection()), this, SLOT(newLocalSocketConnection()));
    connect(socket_, SIGNAL(stateChanged(QLocalSocket::LocalSocketState)),
            this, SLOT(socketStateChanged(QLocalSocket::LocalSocketState))  );
    if (!server_->listen(QCoreApplication::applicationName()))
        {
            if (server_->serverError() == QAbstractSocket::AddressInUseError
                && QFile::exists(server_->serverName()))
                {
                    QFile::remove(server_->serverName());
                    server_->listen(QCoreApplication::applicationName());
                }
        }
}

BackupServer::~BackupServer()
{
    qDebug() << Q_FUNC_INFO;
}

bool BackupServer::parseCmdArgs(const QStringList& args)
{
    bool res = false;

    return res;
}

void BackupServer::start()
{
    tryConnect();
}

void BackupServer::newLocalSocketConnection()
{
    QScopedPointer<QLocalSocket> socket(server_->nextPendingConnection());
    if (!socket)
        return;
    socket->waitForReadyRead(1000);
    QTextStream stream(socket.data());
    QString args,tmp;
}

void BackupServer::socketStateChanged(QLocalSocket::LocalSocketState socketState)
{
    qDebug()<<tr("Соединение : ")<< static_cast<int>(socketState);
    if(socketState == QLocalSocket::ConnectedState)
        {
            qDebug()<<tr("Подконнектились к серверу.");
            server_->close();
            QTimer::singleShot(200,qApp, SLOT(quit()) );
        }
}

void BackupServer::connectTimeout()
{
    qDebug()<< tr("Я один, продолжаю работу ...");
    qDebug()<< tr("Запуск сервера:")<< server_->listen("backup_server_125");
}

void BackupServer::tryConnect()
{
    socket_->connectToServer("backup_server_125");
    QTimer::singleShot(1500, this, SLOT(connectTimeout()));
}
